package com.lyn.module_custom_utils.bitmap;

import android.graphics.Bitmap;
import android.util.LruCache;

/**
 * 图片缓存
 * created by lyn at 2021/10/27
 */
public class BitmapCacheUtil {
    private static class BitmapCacheUtilTypeClass {
        private static BitmapCacheUtil instance = new BitmapCacheUtil();
    }

    public static BitmapCacheUtil getInstance() {
        return BitmapCacheUtil.getInstance();
    }

    private LruCache<String, Bitmap> mMemoryCache;

    public BitmapCacheUtil() {
        // 获取应用最大内存
        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        //用最大内存的1/4来缓存图片
        final int cacheSize = maxMemory / 4;
        mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
            /**
             * 以千字节而不是单位测量项目大小，这对于位图缓存更实用
             */
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount() / 1024;
            }
        };
    }


    public boolean add(String key, Bitmap value) {
        if (key == null || value == null) {
            return false;
        }
        if (mMemoryCache != null) {
            mMemoryCache.put(key, value);
            return true;
        }
        return false;
    }


    public Bitmap get(String key) {
        Bitmap memValue = null;
        if (mMemoryCache != null) {
            memValue = mMemoryCache.get(key);
        }
        return memValue;
    }

}